package com.bulls.demo.hrmsdemo.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.bulls.demo.hrmsdemo.constants.Constants;
import com.bulls.demo.hrmsdemo.form.EmployeeForm;
import com.bulls.demo.hrmsdemo.helper.EmployeeHelper;
import com.bulls.demo.hrmsdemo.service.EmployeeService;
import com.bulls.demo.hrmsdemo.vo.EmployeeVO;

public class EmployeeAction extends Action{
	
	public ActionForward execute(ActionMapping actionMapping,ActionForm actionForm,
			 HttpServletRequest request,HttpServletResponse response)throws Exception{
		System.out.println("action------------>");
		String forwardPath = "failure";
		EmployeeForm form = (EmployeeForm)actionForm;
		String command = request.getParameter("cmd");
		System.out.println("cmd"+command);
		if(Constants.CMD_OPEN.equals(command)){
			forwardPath = executeOpen(request,response,form);
		}else if(Constants.CMD_SAVE.equalsIgnoreCase(form.getMethod())){
			forwardPath = executeSave(request,response,form);
		}else if(Constants.CMD_SEARCH.equalsIgnoreCase(form.getMethod())){
			forwardPath = executeSearch(request,response,form);
		}else if(Constants.CMD_DELETE.equalsIgnoreCase(form.getMethod())){
			forwardPath = executeDelete(request,response,form);
		}
		return actionMapping.findForward(forwardPath);
	}

	private String executeOpen(HttpServletRequest request,
			HttpServletResponse response, EmployeeForm form) {
		
		return "open";
		// TODO Auto-generated method stub
		
	}
	
	private String executeSave(HttpServletRequest request,
			HttpServletResponse response, EmployeeForm form) {
		EmployeeVO employeeVO = new EmployeeVO();
		EmployeeHelper.toDomainObject(form, employeeVO);
		employeeVO = getEmployeeService().save(employeeVO);
		request.getSession().setAttribute("employeeVO", employeeVO);
		return "success";
		// TODO Auto-generated method stub
		
	}
	
	private String executeSearch(HttpServletRequest request,
			HttpServletResponse response, EmployeeForm form) {
		EmployeeVO employeeVO = new EmployeeVO();
		employeeVO = getEmployeeService().search(Long.valueOf(form.getEmployeeid()));
		request.setAttribute("employeeVO", employeeVO);
		return "success";
		// TODO Auto-generated method stub
		
	}
	
	private String executeDelete(HttpServletRequest request,
			HttpServletResponse response, EmployeeForm form) {
		boolean boo = getEmployeeService().delete(form.getEmployeeid());
		request.setAttribute("deleteEmployee", boo);
		return "success";
		// TODO Auto-generated method stub
		
	}
	
	
	public EmployeeService getEmployeeService(){
		EmployeeService employeeService = new EmployeeService();
		return employeeService;
	}


}
